package icu.d4peng.basic.knife4j.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import com.github.xiaoymin.knife4j.extend.filter.BasicFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author d4peng d4peng@qq.com
 * @date 2023-11-25 19:42:44
 */
public class ProductionSecurityFilter extends BasicFilter implements Filter {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProductionSecurityFilter.class);

	/***
	 * 是否生产环境,如果是生成环境,过滤Swagger的相关资源请求
	 */
	private boolean production = false;

	public ProductionSecurityFilter(boolean production) {
		this.production = production;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 判断filterConfig
		Enumeration<String> enumeration = filterConfig.getInitParameterNames();
		// SpringMVC环境中,由此init方法初始化此Filter,SpringBoot环境中则不同
		if (enumeration.hasMoreElements()) {
			setProduction(Boolean.valueOf(filterConfig.getInitParameter("production")));
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		if (production) {
			String uri = httpServletRequest.getRequestURI();
			if (!match(uri)) {
				chain.doFilter(request, response);
			}
			else {
				response.setContentType("text/palin;charset=UTF-8");
				PrintWriter pw = response.getWriter();
				pw.write("You do not have permission to access this page");
				pw.flush();
			}
		}
		else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {

	}

	public boolean isProduction() {
		return production;
	}

	public void setProduction(boolean production) {
		this.production = production;
	}

}
